from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 0.如果当前访问的是登录页面，继续向后走
        if request.path_info in ['/login/', '/image/code/']:
            return None

        # 1.读取当前访问的用户的session信息，如果能读到说明已登录
        if request.session.get('user_info'):
            return None

        # 2.如果读取不到，说明未登录，判断当前访问的url是否是登录页面，如果是则继续向后走
        return redirect('/login/')


# class M1(MiddlewareMixin):
#     """中间件1"""
#     def process_request(self, request):
#         # 如果方法中没有返回值（返回None）继续向后走
#         # 如果方法中返回了一个HttpResponse对象,render,redirect，那么就不会再走后面的中间件和视图函数
#         print('M1 process_request')
#
#     def process_view(self, request, callback, callback_args, callback_kwargs):
#         print('M1 process_view')
#
#     def process_response(self, request, response):
#         print('M1 process_response')
#         return response
#
#
# class M2(MiddlewareMixin):
#     """中间件1"""
#     def process_request(self, request):
#         print('M2 process_request')
#
#     def process_view(self, request, callback, callback_args, callback_kwargs):
#         print('M2 process_view')
#
#     def process_response(self, request, response):
#         print('M2 process_response')
#         return response
